package com.ruoyi.common.filter.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @description: 应用秘钥信息
 * @author:
 * @date: 2021-08-16
 */
@Component
@ConfigurationProperties(prefix = "sign.verify.rsa")
@Data
public class AppSecretProperties {
    private final String DEFAULT_KEY = "default";

    /**
     * 存储配置文件（bootstrap.yml）中每个应用的公钥信息（含主备）
     */
    private Map<String, SecretKey> keys;

    /**
     * 根据应用标识，获取主密钥（RSA公钥）
     *
     * @param appId
     * @return
     */
    public String getMasterPublicKey(String appId) {
        String publicKey = null;
        if (this.keys.containsKey(appId)) {
            publicKey = this.keys.get(appId).getMasterPublicKey();
        }

        if (StringUtils.isEmpty(publicKey) && this.keys.containsKey(DEFAULT_KEY)) {
            publicKey = this.keys.get(DEFAULT_KEY).getMasterPublicKey();
        }
        return publicKey;
    }

    /**
     * 根据应用标识，获取备用密钥（RSA公钥）
     *
     * @param appId
     * @return
     */
    public String getBackupPublicKey(String appId) {
        String publicKey = null;
        if (this.keys.containsKey(appId)) {
            publicKey = this.keys.get(appId).getBackupPublicKey();
        }

        if (StringUtils.isEmpty(publicKey) && this.keys.containsKey(DEFAULT_KEY)) {
            publicKey = this.keys.get(DEFAULT_KEY).getBackupPublicKey();
        }
        return publicKey;
    }

}

